package tutorial.main;


import tutorial.main.control.AppCloseListener;
import tutorial.main.control.AppCloser;
import tutorial.main.control.HTTPProxy;
import tutorial.main.control.Utilities;
import tutorial.main.control.SConfig;
import tutorial.main.control.HTTPProxy.ExcepcionHTTPProxy;
import tutorial.main.data.GestorBDLista;
import tutorial.main.data.ProviderRegistro;
import tutorial.main.vista.GrillaDeEstados;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.TextView;

public class launch extends Activity implements AppCloseListener{

	private Button btnUsuario;
	private TextView txtUsuario;
	
	private static boolean sesionStarted = false;
	
	static final int DIALOG_ERROR_CONN = 0;
	static final int DIALOG_LOADING_ID = 1;
	static final int DIALOG_EXIT = 2;
	static final int DIALOG_ERROR_DB = 3;
	static Context yo;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        yo=this;
        setContentView(R.layout.login);
      
        if(SConfig.getSingleton().getUsuario() != null && SConfig.getSingleton().getUsuario().length() > 0)
        {
        	sesionStarted = true;
        }
        else
        {
        	sesionStarted = false;	
        }
              
        ActivityRedirector();
        
        this.btnUsuario = (Button)this.findViewById(R.id.BotonLogin);
        this.txtUsuario = (TextView)this.findViewById(R.id.txtUsuario);
        
        // Registro para que pueda cerrarse
        AppCloser.registerApplicationCloseListener(this);
        
        // VEO SI HAY ALGO EN EL CAMPO DE USUARIO
        this.txtUsuario.setOnKeyListener(new OnKeyListener() {
        	
			public boolean onKey(View v, int keyCode, KeyEvent event) 
			{
				if(txtUsuario.getText().length() >= 2)
				{
					btnUsuario.setEnabled(true);
				}
				else
				{
					btnUsuario.setEnabled(false);
				}
				if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode==KeyEvent.KEYCODE_ENTER)
				{
				  if(txtUsuario.getText().length() >= 2)
				  {
				      loginEvent();
				  }
				  return true;
				}				
				return false;
			}
		});
        
        // EVENTO Q SE DISPARA CUANDO HAGO CLICK EN EL BOTON DE LOGEO
        this.btnUsuario.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				loginEvent();
			}

			
        });
  
    }

	private void GuardarDatosParaInicioDeSesion(String user, int ci) 
	{
		//Edit: Por ahora solo guardar los datos para iniciar la sesion, los 
		//usa mas tarde cuando se pide sincronizar los eventos
		HTTPProxy.nombre_usuario = user;
		HTTPProxy.clave_usuario  = ci;
	}    
    
    private void loginEvent() {
		int ci=0;
		String user = txtUsuario.getText().toString();
		showDialog(DIALOG_LOADING_ID);

		//Busco si el id ya existe en la BD
		try
		{
			ci=(GestorBDLista.buscarIdUsuario(yo,user));
		}
		catch (SQLiteException e) 
		{
			showDialog(DIALOG_ERROR_DB);
		}
		//No existe, lo pido al servidor
		if(ci==0)
		{
			Log.v("LOG USUARIO", "BUSCO USUARIO EN EL SERVIDOR");
			HTTPProxy proxy = new HTTPProxy();
		
			try {
			
			
				ci = proxy.ObtenerClave(user);
				SConfig.getSingleton().setUsuario(user);//TODO: Kill Singleton
				SConfig.getSingleton().setCi(ci);//TODO: Kill Singleton
				GestorBDLista.guardarIdUsuario(yo, ci, user);
				
			} catch (ExcepcionHTTPProxy e) 
			{
				dismissDialog(DIALOG_LOADING_ID);
				showDialog(DIALOG_ERROR_CONN);
			}
			catch (SQLiteException e) 
			{
				dismissDialog(DIALOG_LOADING_ID);
				showDialog(DIALOG_ERROR_DB);
			}
			
			if(ci!=0)
			{				
				Intent intent = new Intent(launch.this, GrillaDeEstados.class);
				intent.putExtra("usuario",user);
				intent.putExtra("clave_usuario",String.valueOf(ci));
				
				GuardarDatosParaInicioDeSesion(user,ci);
				
				startActivityForResult(intent,Utilities.MAIN);
				
			}
			else
			{
				dismissDialog(DIALOG_LOADING_ID);
				showDialog(DIALOG_ERROR_CONN);
			}
			
		
		}
		else
		{
			Intent intent = new Intent(launch.this, GrillaDeEstados.class);
			intent.putExtra("usuario",user);
			intent.putExtra("clave_usuario",String.valueOf(ci));
			SConfig.getSingleton().setUsuario(user);//TODO: Kill Singleton
			SConfig.getSingleton().setCi(ci);//TODO: Kill Singleton
			
			GuardarDatosParaInicioDeSesion(user,ci);
			
			startActivityForResult(intent,Utilities.MAIN);
		}
	}    
    
   
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode==Utilities.CLOSE_APLICATION)
		{exit();}
		
	}
   
	@Override
	public boolean onPrepareOptionsMenu(android.view.Menu menu)
	{
		menu.clear();
		MenuInflater inflater = new MenuInflater(this);
		inflater.inflate(R.menu.login_menu, menu);
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
	
		case R.id.menu_login_salir:
			showDialog(DIALOG_EXIT);
			return true;
		}
		return false;
	}
	
	@Override
	protected Dialog onCreateDialog(int id) 
	{
	    switch(id) 
	    {
	    
	    case DIALOG_LOADING_ID:
	    	
			ProgressDialog pd = new ProgressDialog(launch.this);
			pd.setMessage((getString(R.string.msje_progresoUsuario)));
			pd.setCancelable(true);
			pd.setIndeterminate(true);
			return pd;
		
	    case DIALOG_EXIT:
	    	return crearDialogoSalir();
	    	
	    	
	    case DIALOG_ERROR_DB:
	    	return new AlertDialog.Builder(launch.this)
            .setIcon(R.drawable.ic_dialog_alert)
            .setTitle(R.string.i_dialog_titulo_errordb_1)
            .setMessage(R.string.i_dialog_errordb_1)
            .setPositiveButton(R.string.aceptar, new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog, int whichButton) 
                {

                }
            })
            .create();	
	    	
	    case DIALOG_ERROR_CONN:
	    	return new AlertDialog.Builder(launch.this)
            .setIcon(R.drawable.ic_dialog_alert)
            .setTitle(R.string.i_dialog_titulo_error_1)
            .setMessage(R.string.i_dialog_error_1)
            .setPositiveButton(R.string.aceptar, new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog, int whichButton) 
                {

                }
            })
            .create();

	    }
	    return null;
	}
	
	//Creacion de dialogo para confirmar cierre de la aplicacion
	private Dialog crearDialogoSalir()
    {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage(getString(R.string.msje_confirmarSalir));
    	builder.setPositiveButton(getString(R.string.si), new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) 
    	           {
    	        	   AppCloser.ExitApp(null);
    	           }
    	       });
    	builder.setNegativeButton(getString(R.string.no), null);
    	AlertDialog dialogoSalir = builder.create();
    	dialogoSalir.setTitle(getString(R.string.salir));
    	return dialogoSalir;
    }
	
	private void exit() {
		//stopService(new Intent(this, NetChangeService.class));
		finish();
		System.exit(0);
	}

	@Override
	public void onAppCloseRequest(Bundle data) 
	{
		runOnUiThread
		(
				new Runnable()
				{
					public void run()
					{
						launch.this.finish();
					}
				}
		);
	}
	
	  private void ActivityRedirector()
	  {
		  if(sesionStarted)
		  {
			  Intent intent = new Intent(this,GrillaDeEstados.class);			
			  startActivity(intent);
		  }  
	  }
	
}